/**
 * Created by udi on 2016/11/28.
 */
// define(["jv"], function () {
//   return {
//     confirm: function () {
//       alert(1);
//     }
//   }
// })


//物流费，配送费 数据在mysql中，单位是元， 其它在 mongodb 中，单位是分。
require(["jv", "vue", "StackBlur", "numberic", "jquery.fly", "mui"], function () {
  var Vue = require("vue");


  Vue.config.ignoredElements = ["kv", "k", "v"];
  var vm;

  var bindVue = function (data) {

    data = jv.extend({
      min_price: 0,
      address: "",
      image: "",
      freight: 0,
      totalFormula: "",
      remark: "",
      video: "http://gd2mqcwezpdbghty65d.exp.bcelive.com/lss-gmpqanu2ddg9bcre/live.m3u8"
    }, data);

    //从 LocalStorage 加载数据
    var storagePrices = JSON.parse(localStorage.storeId == data.productId ? (localStorage.prices || "[]") : "[]");

    var ret = {};
    $.each(data.prices, function (index) {
      this.ori_index = index;
      var ary = ret[this.category];
      if (!ary) {
        ary = [];
        ret[this.category] = ary;
      }
      var price = this;
      var storeItem = storagePrices.filter(function (it) {
        return it.priceId == price.priceId
      })[0];
      this.number = (storeItem || {}).number || 0;
      ary.push(this);
    });

    data.category = ret;

    localStorage.setItem("fuwu_name", data.fuwu_name);

    jv.vm = vm = new Vue({
      el: '#app',
      data: data,
      computed: {
        categoryCount: function () {
          var len = 0;
          for (var i in this.category) {
            len++;
          }
          return len;
        },
        total: function () {
          var ret = 0;
          $.each(this.prices, function () {
            ret += this.price * (this.number || 0);
          });
          return ret;
        },
        freightFee: function () {
          if (!this.total) return 0;
          if (this.total > this.min_price * 100) return 0;
          return this.freight;
        }
      },
      methods: {
        loadedLogo: function (ev) {
          try {
            var size = jv.getImgNaturalSize(ev.target);
            if (size.width) {
              stackBlurImage("blur", "canvas", 16, false);
            }
          } catch (err) {
            document.write(err);
          }
        },
        video_btn_click: function (ev) {
          var $btn = $(ev.target);
          if ($("video").is(":visible")) {
            $btn.html("显示现场视频");
            try {
              $("video").slideUp()[0].pause();
              $(".main").css("height", "calc( 100vh - 13rem )");
            }
            catch (e) {
            }

          }
          else {
            $btn.html("隐藏现场视频");
            try {
              $("video").slideDown()[0].play();
              $(".main").css("height", "calc( 100vh - 13rem - " + $(".video").outerHeight() + "px)");
            }
            catch (e) {
            }
          }
        },
        getImg: function (img) {
          var index = img.indexOf("/media/");

          return img.slice(0, index) + "/media/small/" + img.slice(index + 7) + "_100x100.jpg";
        }
      }
    });

    vm.$nextTick(function () {

      $(".num input").numberic({
        changed: function (val) {
          vm.$data.prices[$(this).closest(".item").attr("index")].number = val;
        }
      });

      setTimeout(function () {
        if ($("video").length && $("video").is(":visible")) {
          $("video")[0].play();

          $(".main").css("height", "calc( 100vh - 13rem - " + $(".video").outerHeight() + "px)");
        }
      }, 2000);


      var offset = $("footer img").offset();
      $(".numberic-add").click(function (event) {
        var flyer = $("<div class='numberic'><span class='numberic-add'></span></div>").clone(); //抛物体对象
        flyer.fly({
          start: {
            left: event.clientX,//抛物体起点横坐标
            top: event.clientY //抛物体起点纵坐标
          },
          end: {
            left: offset.left + 10,//抛物体终点横坐标
            top: offset.top + 10, //抛物体终点纵坐标
          },
          onEnd: function () {
            this.destroy(); //销毁抛物体
          }
        });
      });

      $("#toConfirm").click(function () {
        if (!vm.total) {
          mui.toast("请选择商品!");
          return;
        }

        var prices = vm.prices;

        $.each(prices, function () {
          this.number = this.number || 0;
        });

        jv.extend(localStorage, {
          storeId: location.map.id,
          total: vm.total,
          freight: vm.freight,
          min_price: vm.min_price,
          totalFormula: vm.totalFormula,
          remark: vm.remark,
          prices: JSON.stringify(prices)
        });

        window.location = "confirm";
      });


      var scroll_computing = false;
      $(".con").scroll(function () {
        if (scroll_computing) return;
        scroll_computing = true;

        setTimeout(function () {
          var top_distince = $(".con").offset().top; //滚动条距离顶端值
          var height = $(".con").height();
          var len = $(".nav").children().length;
          var vfirst;
          for (vfirst = 0; vfirst < len; vfirst++) {
            var item_top = $("#cate_" + vfirst).offset().top;
            if (item_top >= top_distince) {

              if (item_top >= (top_distince + height)) {
                vfirst--;
              }

              break;
            }
          }

          $("a.current").removeClass("current");
          $("a[href=\\#cate_" + vfirst + "]").addClass("current");
          scroll_computing = false;
        }, 500);

      })

      $('.nav a').click(function (ev) {
        ev.stopPropagation();
        $(".current").removeClass("current");
        $(this).addClass("current");


        var $obj = $("#cate_" + $(this).attr("href").split("_")[1]);
        var sv = $obj.offset().top + $(".con").scrollTop() - $(".con").offset().top;
        $(".con").scrollTop(sv - 20);

        return false;
      });


      //设置
      // $(".nav").css("marginTop",$("video").height() +"px");
    });
  }

  jv.post("/store/detail?id=" + location.map.id, bindVue);

  // var moved = false, oriHeightY = 0, oriMouseY = 0, maxHeight = $(".video").height();
  // $(document).bind("touchstart", function (ev) {
  //   moved = false;
  //   if (!ev.originalEvent.touches) {
  //     return;
  //   }
  //   if (!$(ev.target).closest(".video").length && !$(ev.target).closest(".header").length && !$(ev.target).closest(".header2").length) {
  //     return;
  //   }
  //
  //   oriHeightY = $(".video").height();
  //   oriMouseY = ev.originalEvent.touches[0].clientY;
  //   moved = true;
  // });
  //
  // if ($("video").length) {
  //   $(document).bind("touchmove", function (ev) {
  //     if (!ev.originalEvent.touches) {
  //       return;
  //     }
  //     if (!moved) return;
  //
  //     var curY = ev.originalEvent.touches[0].clientY;
  //     var dis = curY - oriMouseY;
  //
  //
  //     if (Math.abs(dis) < 1) {
  //       return;
  //     }
  //
  //     moved = true;
  //
  //
  //     if (dis > 0 && oriHeightY + dis >= maxHeight) {
  //       $("video")[0].play();
  //       return;
  //     }
  //     if (oriHeightY + dis < 0) {
  //       return;
  //     }
  //
  //     if (oriHeightY + dis < maxHeight) {
  //       $("video")[0].pause();
  //     }
  //
  //     $(".video").height(oriHeightY + dis + "px");
  //
  //     ev.stopPropagation();
  //     ev.preventDefault();
  //
  //
  //     // if (this.scrollTop > 0 && $(this).isScroll2Bottom()) {
  //     //   ev.stopPropagation();
  //     // }
  //   });
  // }
})
;
